package com.jvyou.thread.d10lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/31 11:46
 * @Description 测试 Lock 锁
 */
public class LockDemo extends Thread {
    static int ticket = 0;
    static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            // 加锁
            lock.lock();
            try {
                if (ticket < 100) {
                    ticket++;
                    System.out.println(getName() + "卖票：" + ticket);
                    Thread.sleep(100);
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        LockDemo t1 = new LockDemo();
        t1.setName("窗口1");
        t1.start();
        LockDemo t2 = new LockDemo();
        t2.setName("窗口2");
        t2.start();
        LockDemo t3 = new LockDemo();
        t3.setName("窗口3");
        t3.start();
    }
}
